/**
 * Created by Handsome.Ho on 2015/10/7.
 */
angular.module('task.services', []).provider('TaskService', function () {

    this.cloudUrl = null;
    var that = this;

    this.$get = function ($http, $rootScope) {

      function loadFromCloud(account, success, fail) {
        $http({
          method: 'GET',
          url: that.cloudUrl + '/tasks/account/' + account
        }).success(function (data) {
          var db = $rootScope.db;
          if (data.bsuccess) {
            var db = $rootScope.db;
            db.transaction(function (tx) {
              angular.forEach(data.data, function (item, index) {
                var uuid = $rootScope.uuid();
                tx.executeSql('INSERT INTO task (id,name,sdt,edt,remote,finish) VALUES (?,?,?,?,?,?)', [uuid, item.name, parseInt(item.sdt), parseInt(item.edt), 1, 0], function () {
                }, function () {
                });
                console.log(item);
              });
            });
          }
        });
      }

      function openDB() {
        return openDatabase('easy-schedule', '1.0', 'easy-schedule', 2 * 1024 * 1024);
      }

      function success() {

      }

      function fail(tx, err) {
        alert(err.message);
      }

      function init() {
        var db = openDB();
        db.transaction(function (tx) {
          tx.executeSql('DROP TABLE task', [], success, fail);
          tx.executeSql('CREATE TABLE IF NOT EXISTS task (id unique, name,sdt,edt,remote,finish)', [], success, fail);
          tx.executeSql('delete from task', [], success, fail);
          var sdt = new Date(2015, 9, 9).Format("yyyyMMdd");
          var edt = new Date(2015, 9, 10).Format("yyyyMMdd");
          var sdt2 = new Date(2015, 9, 9).Format("yyyyMMdd");
          var edt2 = new Date(2015, 9, 9).Format("yyyyMMdd");
          var sdt3 = new Date(2015, 9, 15).Format("yyyyMMdd");
          var edt3 = new Date(2015, 9, 17).Format("yyyyMMdd");
          var sdt4 = new Date(2015, 10, 9).Format("yyyyMMdd");
          var edt4 = new Date(2015, 10, 11).Format("yyyyMMdd");
          tx.executeSql('INSERT INTO task (id,name,sdt,edt,remote,finish) VALUES (?,?,?,?,?,?)', ['1', '需求调研', parseInt(sdt), parseInt(edt), '0', '1'], success, fail);
          tx.executeSql('INSERT INTO task (id,name,sdt,edt,remote,finish) VALUES (?,?,?,?,?,?)', ['2', '概要设计', parseInt(sdt2), parseInt(edt2), '0', '0'], success, fail);
          tx.executeSql('INSERT INTO task (id,name,sdt,edt,remote,finish) VALUES (?,?,?,?,?,?)', ['3', '详细设计', parseInt(sdt3), parseInt(edt3), '0', '0'], success, fail);
          tx.executeSql('INSERT INTO task (id,name,sdt,edt,remote,finish) VALUES (?,?,?,?,?,?)', ['4', '编码', parseInt(sdt4), parseInt(edt4), '0', '0'], success, fail);
        });
      }


      function getTasksByDate(dto) {
        var db = openDB();
        var dt = dto.dt.Format("yyyyMMdd");
        var time = parseInt(dt);
        db.transaction(function (tx) {
          tx.executeSql('SELECT * FROM task where sdt<=? and edt>=?', [time, time], function (tx, results) {
            var len = results.rows.length;
            var datas = [];
            for (var i = 0; i < len; i++) {
              datas[i] = results.rows.item(i);
            }
            if (dto.callback) {
              dto.callback(datas);
            }
          });
        });
      }

      function getTaskByMonth(dto) {
        //init();
        var year = dto.year + '';
        var month = dto.month + '';
        if (year.length == 1) {
          year = '0' + year;
        }
        if (month.length == 1) {
          month = '0' + month;
        }
        var stime = year + month + '01';
        var etime = year + month + '31';
        var db = $rootScope.db;
        db.transaction(function (tx) {
          tx.executeSql('SELECT * FROM task where edt>=' + stime + ' and sdt<=' + etime, [], function (tx, results) {
            var len = results.rows.length;
            var datas = [];

            for (var i = 0; i < len; i++) {
              var item = results.rows.item(i);
              var sm = (item.sdt + '').substring(4, 6);
              var sd = (item.sdt + '').substring(6, 8);
              var em = (item.edt + '').substring(4, 6);
              var ed = (item.edt + '').substring(6, 8);
              item.dt = sm + '/' + sd + '-' + em + '/' + ed;
              datas[i] = item;

            }
            for (var i = 0; i < datas.length; i++) {
              var index = 0;
              for (var j = i; j < datas.length; j++) {
                if (datas[i].edt >= datas[j].sdt && datas[i].sdt <= datas[j].edt) {
                  index++
                }
              }
              datas[i].index = index;
            }
            if (dto.callback) {
              dto.callback(datas);
            }
          });
        });
      }

      function countTodo(cfg) {
        var db = $rootScope.db;
        var count = 0;
        db.transaction(function (tx) {
          tx.executeSql('select count(1) c from task where finish=?', ['0'], function (tx, results) {
            if (results.rows.length > 0) {
              count = results.rows[0].c;
              if (cfg.callback) {
                cfg.callback(count);
              }
            }
          });
        });
        return count;
      }

      function listTodo(cfg) {
        var db = $rootScope.db;
        db.transaction(function (tx) {
          tx.executeSql('select * from task where finish=?', ['0'], function (tx, results) {
            var len = results.rows.length;
            var datas = [];
            for (var i = 0; i < len; i++) {
              datas[i] = new TaskVO(results.rows.item(i));
            }
            if(cfg.callback){
              cfg.callback(datas);
            }
          });
        });
      }

      function TaskVO(item) {
        var sm = (item.sdt + '').substring(4, 6);
        var sd = (item.sdt + '').substring(6, 8);
        var em = (item.edt + '').substring(4, 6);
        var ed = (item.edt + '').substring(6, 8);
        var dt = sm + '/' + sd + '-' + em + '/' + ed;
        var obj = {};
        for (var p in item) {
          obj[p] = item[p];
        }
        obj.dt = dt;
        return obj;
      }

      return {
        getTasksByDate: getTasksByDate,
        getTaskByMonth: getTaskByMonth,
        loadFromCloud: loadFromCloud,
        countTodo: countTodo,
        listTodo: listTodo
      };
    }
  }
);
